import router from 'umi/router';
import fetch from 'dva/fetch';
import { notification, Modal } from 'antd';
import { reqTimeout } from '../../config';

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const checkStatus = response => {
  if (response.status >= 400) {
    const errortext = codeMessage[response.status] || response.statusText;
    notification.error({
      message: `请求错误 ${response.status}: ${response.url}`,
      description: errortext,
    });
    if (response.status === 403) {
      router.push('/exception/403');
    } else if (response.status >= 404 && response.status < 422) {
      router.push('/exception/404');
    } else if (response.status <= 504 && response.status >= 500) {
      router.push('/exception/500');
    }
  }
  return response;
};

export default function request(
  url,
  options,
  needGetStatus,
  needReadText,
  reqType,
  func,
  second = reqTimeout
) {
  const newOptions = options;
  if (newOptions.method === 'POST') {
    if (reqType === 'json') {
      // json请求
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        ...newOptions.headers,
      };
      newOptions.body = JSON.stringify(newOptions.body);
    } else if (reqType === 'form') {
      // form请求
      newOptions.headers = {
        Accept: 'application/json',
        mode: 'no-cors',
        ...newOptions.headers,
      };
    }
  }

  return Promise.race([
    fetch(url, newOptions),
    new Promise((resolve, reject) => {
      setTimeout(() => reject(new Error('网络请求超时')), 1000 * second);
    }),
  ])
    .then(checkStatus)
    .then(response => {
      if (newOptions.method === 'DELETE' || response.status === 204) return response.text();
      if (needGetStatus) {
        // 存储网络请求状态到cookie, 供"系统资源"页面使用
        const day = 7;
        const exp = new Date();
        exp.setTime(exp.getTime() + day * 24 * 60 * 60 * 1000);
        document.cookie = 'netStatus=' + escape(response.status) + ';expires=' + exp.toGMTString();
      }
      if (needReadText) return response.text();
      if (func)
        response.json().then(data => {
          func(data);
        });
      return response.json();
    })
    .then(response2 => {
      if (response2) {
        if (!response2.success && response2.status === 401) {
          // 状态码"401"来源于: dgej_admin/src/common/web/controller/TokenCheckRequest:
          // return nil, &JsonMsg{false, "登录状态已失效，请重新登录！", 401}
          Modal.confirm({
            title: '登录状态异常',
            content: response2.msg,
            okText: '好',
            cancelText: '不',
            onOk: () => {
              document.location.hash = '#/user/login';
              // document.location.pathname = '/user/login';
              // window.g_app._store.dispatch({ type: 'user/login' });
            },
          });
        }
      } else {
        notification.error({ message: url, description: '接口返回为null' });
      }
      return response2;
    })
    .catch(err => {
      let description = err.toString();
      if (description.indexOf('Failed to fetch') >= 0) description = '网络连接失败';
      notification.error({ message: url, description });
      return {
        msg: description,
        success: false,
        status: -1,
      };
    });
}
